<template>
  <!-- 头部 -->
  <div class="header" style="width: 100%">
    <div style="width: 100%;display: flex; align-items: center; justify-content: space-between; ">
      <!-- 新增按钮 -->
      <el-button :icon="Plus" type="primary" @click="open(null)" size="medium">
        新增
      </el-button>

      <!-- 离职按钮 -->
      <el-popconfirm
        confirm-button-text="是"
        cancel-button-text="否"
        :icon="InfoFilled"
        icon-color="#626AEF"
        title="是否离职"
        @confirm="confirmEvent"
        @cancel="cancelEvent"
      >
        <template #reference>
          <el-button :icon="Delete" type="danger" size="medium">
            离职
          </el-button>
        </template>
      </el-popconfirm>

      <!-- 搜索和重置按钮 -->

      <el-form
        inline
        style="margin-top: 14px; flex-grow: 1; margin-left: 20px; display: flex"
      >
        <!-- 部门 -->
        <el-form-item>
          <el-select
            v-model="search.department"
            placeholder="请选择部门"
            style="width: 220px"
            size="medium"
          >
            <el-option
              v-for="uniquePd in uniquePds"
              :key="uniquePd.id"
              :label="uniquePd"
              :value="uniquePd"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 人名 -->
        <el-form-item>
          <el-input
            v-model="search.name"
            placeholder="请输入名称"
            style="width: 220px"
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item style="display: flex; flex-wrap: nowrap ">
          <el-button type="primary" @click="onSearch" size="medium">
            搜索
          </el-button>
          <el-button @click="onReset" size="medium"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

  <!-- 文章列表 -->
  <el-table
    :data="pagedEmployees"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="40"></el-table-column>
    <el-table-column prop="id" label="编号" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="sex" label="性别" />
    <el-table-column prop="department" label="部门" />
    <el-table-column prop="position" label="职位" />
    <el-table-column prop="phone" label="手机号" width="125" />
    <el-table-column prop="email" label="邮箱" width="175" />
    <el-table-column prop="startDate" label="入职日期" width="105" />

    <el-table-column prop="status" label="状态">
      <template #default="scope">
        <el-tag :type="scope.row.status ? 'success' : 'danger'">{{
          scope.row.status === 1 ? '在职' : '离职'
        }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="open(scope.row)">改</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增 编辑 弹窗 -->
  <el-dialog
    v-model="dialogFormVisable"
    :before-close="beforeClose"
    :title="title"
    width="500"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      label-position="left"
      :model="form"
      :rules="rules"
    >
      <el-form-item v-show="false" prop="id">
        <el-input v-model="form.id"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select v-model="form.department" placeholder="请选择部门职位">
          <el-option
            v-for="uniquePd in uniquePds"
            :key="uniquePd.id"
            :label="uniquePd"
            :value="uniquePd"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="职位" prop="position">
        <el-select v-model="form.position" placeholder="请选择职位">
          <el-option
            v-for="uniquePst in uniquePosition"
            :key="uniquePst.id"
            :label="uniquePst"
            :value="uniquePst"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="form.startDate"
          type="date"
          placeholder="选择日期"
          :size="size"
          @change="updateStartDate"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">在职</el-radio>
          <el-radio :value="0">离职</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm(formRef, title)"
          >确认</el-button
        >
      </div>
    </template>
  </el-dialog>

  <!-- 分页条 -->
  <pagi-nation
    :total="employees.total"
    :allData="allEmployees"
    @update:Data="updateEmployees"
  ></pagi-nation>
</template>

<script setup>
import { reactive, ref, computed, onMounted, nextTick, watchEffect } from 'vue'
import { Plus, InfoFilled, Delete } from '@element-plus/icons-vue'
import { useEmployeeStore } from '@/stores'
import { employeeAdd, employeeEdit, employeelot } from '@/api/employee'
import dayjs from 'dayjs'

const updateStartDate = (value) => {
  if (value) {
    form.startDate = dayjs(value).format('YYYY-MM-DD')
  }
}

// 调用store实例
const employeeStore = useEmployeeStore()

onMounted(async () => {
  await getEmployeeAll()
  pagedEmployees.value = allEmployees.value.slice(0, 5)
})

//列表数据
const pagedEmployees = ref([])
// 接收子组件传递回来的分页数据
const updateEmployees = (newEmployees) => {
  pagedEmployees.value = newEmployees.value
  console.log(newEmployees, 'newEmployees')
}

// 员工所有信息查询
const getEmployeeAll = async () => {
  await employeeStore.fetchEmployeeAll()
  Object.assign(employees, employeeStore.employees) //整体赋值
  allEmployees.value = employeeStore.allEmployees
  employees.total = allEmployees.value.length
}
// 模糊查询
const onSearch = async () => {
  await employeeStore.fetchEmployeeSearch(search)

  allEmployees.value = employeeStore.allEmployees
  employees.total = employeeStore.employees.total
  // getEmployeeAll()
}
// 重置
const onReset = () => {
  search.department = ''
  search.name = ''
  getEmployeeAll()
}

//所有员工信息
const employees = reactive({
  employee: [],
  total: 3
})
//所有员工信息--用于分页
const allEmployees = ref([])
//模糊查询需要的数据
const search = reactive({
  department: '',
  name: ''
})

// 使用computed计算不同的部门数组,职位数组
const uniquePds = computed(() => {
  const pds = new Set(employees.employee.map((emp) => emp.department))
  return Array.from(pds)
})
// 使用computed计算不同的部门数组
const uniquePosition = computed(() => {
  const positions = new Set(employees.employee.map((emp) => emp.position))
  return Array.from(positions)
})

//定义多选框选中的数据
const selectTableData = ref([])
//多选框
const handleSelectionChange = (val) => {
  //拿到勾选的数据
  selectTableData.value = val.map((item) => ({ id: item.id }))
}
//删除 确认
const confirmEvent = async () => {
  //没有勾选 选了确定按钮 提示信息
  if (!selectTableData.value.length) {
    return ElMessage.warning('请选择至少一项数据')
  } else {
    //调用离职接口
    // console.log(selectTableData.value, '选择的数据')[{id:,id:}]
    const ids = selectTableData.value.map((item) => item.id)
    const res = await employeelot(ids)
    // console.log(res, '删除')
    if (res.code === 200) {
      ElMessage.success('员工辞退成功')
    }
    getEmployeeAll()
  }
}

//点击 编辑 添加 按钮
const title = ref('员工信息添加')
const open = (rowData) => {
  dialogFormVisable.value = true
  nextTick(() => {
    //如果是编辑，有参数
    if (rowData) {
      title.value = '员工信息修改'
      //浅拷贝
      Object.assign(form, rowData) //当前的rowData数据给form
    } else {
      title.value = '员工信息添加'
    }
  })
}

//新增 编辑
const dialogFormVisable = ref(false)
//关闭前的函数
const beforeClose = () => {
  //关闭弹窗
  dialogFormVisable.value = false
  //清空当前的form
  formRef.value.resetFields()
}
//拿到当前的el-form示例
const formRef = ref()
//el-form 的表单数据
const form = reactive({
  // id: '',
  name: '',
  sex: '',
  phone: '',
  email: '',
  department: '',
  position: '',
  startDate: '',
  status: '1'
})
//表单校验
const rules = reactive({
  name: [{ required: true, trigger: 'blur', message: '请填写昵称' }],
  sex: [{ required: true, trigger: 'blur', message: '请选择性别' }],
  phone: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入手机号'
    },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('手机号不能为空'))
        } else {
          const phoneReg =
            /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
          phoneReg.test(value)
            ? callback()
            : callback(new Error('手机号格式不正确'))
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入邮箱地址'
    },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('邮箱地址不能为空'))
        } else {
          const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
          emailReg.test(value)
            ? callback()
            : callback(new Error('邮箱地址格式不正确'))
        }
      },
      trigger: 'blur'
    }
  ],
  status: [{ required: true, trigger: 'blur', message: '请选择状态' }]
})
//实现新增--编辑 表单提交--校验（点击确定按钮）点击编辑 出现这个弹窗，点击确定 更新列表
const confirm = async (formEl, title) => {
  if (!formEl) return

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (title === '员工信息添加') {
        const res = await employeeAdd(form)
        // form.startDate = dayjs(form.startDate).format('YYYY-MM-DD')
        beforeClose()
        if (res.code === 200) {
          ElMessage.success('员工添加成功')
          getEmployeeAll()
        }
      } else {
        const res = await employeeEdit(form)
        beforeClose()
        if (res.code === 200) {
          ElMessage.success('员工编辑成功')
          getEmployeeAll()
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

watchEffect(() => {
  if (allEmployees.value && allEmployees.value.length > 0) {
    pagedEmployees.value = allEmployees.value.slice(0, 5)
  } else {
    pagedEmployees.value = []
  }
})
</script>

<style lang="less" scoped>
.header {
  box-sizing: border-box;
  padding: 10px 0 10px 20px;
  background-color: #fff;
  display: flex;
  align-items: center;
}
</style>
